package itstudio.instructor.fragment;

import itstudio.app.wq.R;
import itstudio.instructor.adapter.AddImageAdapter;
import itstudio.instructor.config.Config;
import itstudio.instructor.config.ImageOptionsUtil;
import itstudio.instructor.config.MyApplication;
import itstudio.instructor.entity.News;
import itstudio.instructor.http.TwitterRestClient;
import itstudio.instructor.image.local.localImageFirstActivity;
import itstudio.instructor.service.DatebaseService;
import itstudio.instructor.ui.DraftsEditActivity;
import itstudio.instructor.util.BitMapUtil;
import itstudio.instructor.util.FileUtil;
import itstudio.instructor.util.TimeUtil;
import itstudio.instructor.util.ToastUtil;
import itstudio.instructor.widget.ActionSheetPic;
import itstudio.instructor.widget.ActionSheetPic.OnActionSheetSelected;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import me.storm.ninegag.view.swipeback.ImageViewActivity;
import org.apache.http.Header;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

/**
 * @Description 设置 Fragment
 * 
 * @author MR.Wang
 * 
 * @date 2014-7-5 上午1:13:26
 * 
 * @version V1.0
 */

@SuppressLint("ValidFragment")
public class FragmentSend extends Fragment implements OnActionSheetSelected {

	// view
	private View rootView;

	EditText title_et = null;
	EditText content_et = null;
	TextView send_tv = null;
	TextView drafts_tv = null;
	private GridView gridview;
	DisplayImageOptions options;
	// data
	private Context context;
	private List<String> picList = new ArrayList<String>();// gridview 中的图片
	private String photPath; // 拍照保存 的图片位置
	private String newPicPath = null; // 上传的图片位置
	private int newsPicNum; // 待上传的图片个数

	private static FragmentSend singleton;

	public static FragmentSend getInstance(Context context) {
		if (singleton == null) {
			singleton = new FragmentSend(context);
		}
		return singleton;
	}

	private FragmentSend(Context context) {

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (rootView == null) {
			rootView = inflater.inflate(R.layout.fragment_send, container,
					false);

			context = inflater.getContext();
			if (picList.size() == 0) {
				picList.add("drawable://" + R.drawable.qzone_photo_btn_add);
			}
			options = ImageOptionsUtil.newsImageOptions();
			initView(rootView);
		}
		ViewGroup parent = (ViewGroup) rootView.getParent();
		if (parent != null) {
			parent.removeView(rootView);
		}
		return rootView;

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (Config.IS_SEND) {
			send_tv.setText(R.string.send_ing);
			AddImageAdapter adapter = new AddImageAdapter(picList, context,
					options);
			gridview.setAdapter(adapter);
		}
	}

	public void initView(View view) {
		// TODO Auto-generated method stub
		title_et = (EditText) view.findViewById(R.id.title_hint);
		content_et = (EditText) view.findViewById(R.id.content_edt);
		send_tv = (TextView) view.findViewById(R.id.submit_tv);
		drafts_tv = (TextView) view.findViewById(R.id.drafts_tv);
		gridview = (GridView) view.findViewById(R.id.gridview);
		gridview.setAdapter(new AddImageAdapter(picList, context, options));
		send_tv.setOnClickListener(clickListener);
		drafts_tv.setOnClickListener(clickListener);

		gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				if(Config.IS_SEND == true){
					return;
				}// 标记发布中)
				if (position == picList.size() - 1) {
					ActionSheetPic.showSheet(context, FragmentSend.this);
				} else {

					Intent intent = new Intent(context, ImageViewActivity.class);
					intent.putExtra(ImageViewActivity.IMAGE_URL,
							picList.get(position));
					startActivityForResult(intent, Config.REQUEST_PREVIEW_PIC);
				}
			}

		});
	}

	BaseAdapter adapter = new BaseAdapter() {

		// 取得适配器中的视图
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// 将适配器中缓冲的视图控件返回
			View view = convertView;

			if (view == null) {
				// 将gallery_item.xml适配到View中
				LayoutInflater inflater = LayoutInflater.from(context);
				view = inflater.inflate(R.layout.grid_view_item, null);
			}

			// 查找gallery_item.xml中的ImageView控件
			ImageView imageView = (ImageView) view.findViewById(R.id.book_name);
			return view;
		}

		@Override
		public long getItemId(int position) {

			return position;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public int getCount() {

			return picList.size();
		}
	};

	OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.submit_tv:
				
				pubNews();
				break;
			case R.id.drafts_tv:
				saveDrafts();
				break;

			default:
				break;
			}
		}
	};

	@Override
	public void onClick(int whichButton) {
		// TODO Auto-generated method stub
		switch (whichButton) {

		case R.id.local_pic:

			getLocalPohot();
			break;

		case R.id.take_photo:
			takePhoto();
			break;

		default:
			break;
		}

	}

	private void takePhoto() {

		Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		cameraIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0); 
		String path = Config.TEMP_PATH;
		if (FileUtil.makeDir(path)) {

			String photoName = TimeUtil.dateToString(new Date(),
					TimeUtil.FORMAT_DATE_TIME_SECOND) + ".png";
			photPath = Config.TEMP_PATH + photoName;
			Uri imageUri = Uri.fromFile(new File(path, photoName));
			cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
			startActivityForResult(cameraIntent, 1);
		} else {

			ToastUtil.showErrorMsg((Activity)context, R.string.error_sdcard_null);
		}

	}

	private void getLocalPohot() {
		Intent intent = new Intent();
		intent.setClass(context, localImageFirstActivity.class);
		// List<String> tempList = picList;
		intent.putStringArrayListExtra("alredyChoose",
				(ArrayList<String>) picList);
		startActivityForResult(intent, Config.REQUEST_LOCAL_PIC);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		// 相机返回
		if (resultCode == Activity.RESULT_OK) {
			picList.remove(picList.size() - 1);
			picList.add(photPath);
			picList.add("drawable://" + R.drawable.qzone_photo_btn_add);
			AddImageAdapter adapter = new AddImageAdapter(picList, context,
					options);
			gridview.setAdapter(adapter);
		}
		// 预览activity 返回
		else if (resultCode == Config.RESULT_PREVIEW_PIC) {
			String path = data.getStringExtra(ImageViewActivity.IMAGE_URL);
			picList.remove(path);
			AddImageAdapter adapter = new AddImageAdapter(picList, context,
					options);
			gridview.setAdapter(adapter);
		}
		// 本地照片 返回
		else if (resultCode == Config.RESULT_LOCAL_IMG) {

			picList = data.getStringArrayListExtra("alredyChoose");
			picList.add("drawable://" + R.drawable.qzone_photo_btn_add);
			AddImageAdapter adapter = new AddImageAdapter(picList, context,
					options);
			gridview.setAdapter(adapter);
		}
	}

	/**
	 * 存草稿
	 * 
	 * @param title
	 * @param content
	 */
	protected void saveDrafts() {

		if (Config.IS_SEND) {

			ToastUtil.showErrorMsg((Activity)context, R.string.wait_send);
			return;
		}
		if (TextUtils.isEmpty(title_et.getText())
				|| TextUtils.isEmpty(content_et.getText())) {

			ToastUtil.showErrorMsg(getActivity(), R.string.error_news_null);
			return;
		}
		if (title_et.getText().length() > 35) {
			ToastUtil.showErrorMsg(getActivity(), R.string.error_news_tolong);
			return;
		}
		if (picList.size()> 9) {
			
			ToastUtil.showErrorMsg((Activity)context, R.string.error_pic_tomuch);
			return;
		}
		String title = title_et.getText().toString();
		String content = content_et.getText().toString();
		// 将List<String>转换为String[]
		StringBuffer sb = new StringBuffer();
		if (picList.size() > 1) {
			for (int i = 0; i < picList.size() - 1; i++) {

				if (i == picList.size() - 2) {
					sb.append(picList.get(i));

				} else {
					sb.append(picList.get(i) + ";");
				}

			}
		}

		DatebaseService service = new DatebaseService(context);

		//获取当前时间
		String curDate = TimeUtil.dateToString(new Date(),TimeUtil.FORMAT_DATE);
		News news = new News(title, content, sb.toString(), null,curDate);
		service.insertData(news);
		ToastUtil.showSuccessMsg((Activity)context, R.string.success_drafts);
		picList.clear();
		picList.add("drawable://" + R.drawable.qzone_photo_btn_add);
		title_et.setText("");
		content_et.setText("");
		AddImageAdapter adapter = new AddImageAdapter(picList, context, options);
		gridview.setAdapter(adapter);

	}

	/**
	 * @Description 发布news 验证
	 */
	protected void pubNews() {
		// TODO Auto-generated method stub
		
		if (Config.IS_SEND) {

			ToastUtil.showErrorMsg((Activity)context, R.string.wait_send);
			return;
		}
		if (TextUtils.isEmpty(title_et.getText())
				|| TextUtils.isEmpty(content_et.getText())) {
			
			ToastUtil.showErrorMsg((Activity)context, R.string.error_news_null);
			return;
		}
		if (title_et.getText().length() > 35) {

			ToastUtil.showErrorMsg((Activity)context, R.string.error_news_tolong);
			return;
		}
		
		if (picList.size()> 9) {
			
			ToastUtil.showErrorMsg((Activity)context, R.string.error_pic_tomuch);
			return;
		}
		send_tv.setText(R.string.send_ing);
		Config.IS_SEND = true;// 标记发布中
		final String title = title_et.getText().toString();
		final String content = content_et.getText().toString();
		// 有图
		
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (picList.size() > 1) {
					
					newsPicNum = picList.size()-1;
					for (int i =0;i<picList.size()-1 ;i++) {
						String picPath = picList.get(i);
						Bitmap camorabitmap = BitMapUtil
								.decodeBitmap(picPath, 600, 800);
						String filename = picPath
								.substring(picPath.lastIndexOf("/") + 1);
						File file = FileUtil.saveBitmap(Config.TEMP_PATH, filename,
								camorabitmap);// 压缩
						uploadPic(file,title, content);
					}

				}

				else {
					publishNews(title, content);
				}
			}
		},400);


	}

	/**
	 * @Description 上传图片
	 * @param file
	 */
	private void uploadPic(File file,final String title, final String content) {
		RequestParams params = new RequestParams();
		TwitterRestClient.client.addHeader("Content-Type",
				"multipart/form-data");
		try {
			params.put("file", file);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		TwitterRestClient.post(Config.AC_NEWS_PIC, params,
				new AsyncHttpResponseHandler() {
					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						// TODO Auto-generated method stub
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1,
							byte[] response) {
						if (newPicPath != null) {
							newPicPath = newPicPath + new String(response)
									+ ";";
						} else {
							newPicPath = new String(response) + ";";
						}
						newsPicNum = newsPicNum - 1;
						if (newsPicNum == 0) {
							newPicPath = newPicPath.substring(0,
									newPicPath.length() - 1);
							publishNews(title, content);
						}
					}
				});
	}

	/**
	 * @Description 发布news
	 * @param title
	 * @param content
	 */
	private void publishNews(String title, String content) {
		RequestParams params = new RequestParams();
		params.put("news.title", title);
		params.put("news.content", content);
		if (newPicPath != null) {
			params.put("news.newsPics", newPicPath);
		}
		TwitterRestClient.post(Config.AC_NEWS_SEND, params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1,
							byte[] response, Throwable arg3) {
						// TODO Auto-generated method stub

						ToastUtil.showErrorMsg((Activity)context, R.string.fail_send);
						Config.IS_SEND = false;
						send_tv.setText(R.string.send);
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] data) {
						// 发布完成
						String response = new String(data);
						if (response.indexOf(Config.SUCCESS) != -1) {
							picList.clear();
							picList.add("drawable://"
									+ R.drawable.qzone_photo_btn_add);
							title_et.setText("");
							content_et.setText("");
							AddImageAdapter adapter = new AddImageAdapter(
									picList, context, options);
							gridview.setAdapter(adapter);
							MyApplication.user.setNewsNum(MyApplication.user
									.getNewsNum() + 1);
							newPicPath=null;
							ToastUtil.showSuccessMsg((Activity)context, R.string.success_send);
						} else {
							
							ToastUtil.showErrorMsg((Activity)context, R.string.fail_send);

						}
						send_tv.setText(R.string.send);
						Config.IS_SEND = false;
					}
				});
	}
}
